package com.graphhopper;

import com.graphhopper.json.Statement;
import com.graphhopper.util.CustomModel;
import com.graphhopper.util.Helper;
import com.graphhopper.util.PMap;
import com.graphhopper.util.shapes.GHPoint;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * 货汽车路线规划校验对象
 */
public class GHRRequestTruckCheck {
    /**
     * 货车路线规划校验设和默认值
     * @param request
     */
    public static void checkTruckAndSetDefault(GHRequest request) {
        if(request == null){
            throw new IllegalArgumentException("请求参数不能为空！");
        }
        List<GHPoint> points=request.getPoints();
        if(points == null || points.size() < 2){
            throw new IllegalArgumentException("路线规划至少需要两个坐标点！");
        }
        int row=points.size();
        for(int i=0;i<row;i++){
            if(!points.get(i).isValid()){
                throw new IllegalArgumentException("坐标点["+(i+1)+"]无效！");
            }
            //判断是否在国内坐标 todo
//            if(!Helper.isInsideChina(points.get(i).getLat(),points.get(i).getLon())){
//                throw new IllegalArgumentException("坐标点["+(i+1)+"]不在国内！");
//            }
        }

        String profile = request.getProfile();
        if(StringUtils.isBlank(profile)){
            request.setProfile("truck");
        }

        if(!checkTruck(request.getProfile())){
            throw new IllegalArgumentException("不支持的profile："+profile+",该接口只支持：truck和small_truck两种类型");
        }

        PMap pMap= request.getHints();
        if(pMap == null){
            pMap=new PMap();
        }
        boolean flag= pMap.has("points_encoded");
        if(!flag){
            pMap.putObject("points_encoded",false);
        }
        pMap.putObject("ch.disable",true);
        if(request.getCustomModel() == null){
            request.setCustomModel(new CustomModel());
        }

        if (!pMap.has("alternative_route.max_paths")){
            //默认3条路线
            pMap.putObject("alternative_route.max_paths",3);
        }

        if(StringUtils.isBlank(request.getAlgorithm())){
            request.setAlgorithm("alternative_route");
        }

        //设置最大速度
        Double maxSpeed=request.getMaxSpeed();
        if(maxSpeed != null && maxSpeed > 0){
            request.getCustomModel().getSpeed().add( Statement.If("true", Statement.Op.LIMIT, maxSpeed+""));
        }

    }

    public static boolean checkTruck(String profile) {
        if ("truck".equals(profile)){
            return true;
        }
        if("small_truck".equals(profile)){
            return true;
        }
        return false;
    }
}
